const koa = require("koa");
const koaRouter = require("@koa/router");
const KoaSession = require("koa-session");

const app = new koa();

const session = KoaSession(
  {
    key: "sessionid", //cookie 的key值
    maxAge: 5 * 60 * 1000, //过期时间
    httpOnly: true, //不允许通过js获取cookie
    rolling: true, //每次响应时，刷新session的有效期
    signed: true, //是否使用signed前面认证，防止数据被篡改
  },
  app
);

//加盐  cookie存储是还会多sessionid.sig
app.keys = ["hasdflh", "sdkfaj"];
app.use(session);

const userRouter = new koaRouter({ prefix: "/user" });

userRouter.get("/login", (ctx, next) => {
  ctx.session.user = {
    id: 110,
    name: "why",
  };
  ctx.body = "session设置成功";
});

userRouter.get("/demo", (ctx, next) => {
  const user = ctx.session.user;
  ctx.body = user;
});

app.use(userRouter.routes());
app.use(userRouter.allowedMethods());

app.listen("9000", () => {
  console.log("koa服务器开启");
});
